<?php

namespace App\Http\Controllers\Api;

use App\Model\AdminLog;
use App\Model\CheckRecord;
use App\Model\CostStatistics;
use App\Model\FinanceCharmStream;
use App\Model\FinanceDiamondStream;
use App\Model\FinanceRechargeOrder;
use App\Model\FinanceWealthStream;
use App\Model\FinanceWithdrawOrder;
use App\Model\Number;
use App\Model\OperationLogs;
use App\Model\UserCloud;
use App\Model\UserVerify;
use App\Model\Union;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use App\Model\Api\Account;

class AccountController extends BaseController
{
    protected $api;
    protected $model;

    public function __construct(Request $request, FinanceWithdrawOrder $financeWithdrawOrder)
    {
        parent::__construct($request);
        $this->model = $financeWithdrawOrder;
        $this->api = new Account();
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $res = $this->model->getListV2($request);

        return $this->toJson(self::SUCCESS, $res);
    }

    /**
     * 更新订单状态
     * @param Request $request
     * @return \Illuminate\Http\Response
     */
    public function updateOrderStatus(Request $request)
    {
        $orderSn = $request->input('order_sn', '');
        $status = $request->input('status', 0);
        $image = $request->input('image', '');
        if($orderSn == '' || $status == 0) {
            return $this->toJson(self::ERROR);
        }
        // 获取当前登录用户ID
        $admin = $this->user;
        $adminId = $admin['id'];
        $res = $this->api->updateOrderStatus($orderSn, $status, $image, $adminId);
        if(!$res) {
            return $this->toJson(self::ERROR);
        }
        return $this->toJson(self::SUCCESS);
    }

    /**
     * 提现/驳回
     */
    public function setStatus(Request $request, $order_id)
    {
        $pay_status = (int)$request->input('status');
        $order_sn = $request->input('order_sn');
        $pay_type = (int)$request->input('pay_type');

        $res = [];
        $data = ['order_sn'=>$order_sn];
        if ($pay_status === 3) {
            // //贝灵斯
            // if ($pay_type === 7) {
            //     $res = curl_request(getKkaudioApiUrl() . '/inner/finance/withdraw/pay/bls_order', $data);
            // }
            // //慧用工
            if ($pay_type === 8) {
                $res = curl_request(getKkaudioApiUrl() . '/inner/finance/withdrawPayAlipayOrder', $data);
            }
            //支付宝
            if ($pay_type === 9) {
                $res = curl_request(getKkaudioApiUrl() . '/inner/finance/withdrawPayAlipayOrder', $data);
            }
        } elseif ($pay_status === 2) {
            $res = curl_request(getKkaudioApiUrl() . '/inner/finance/withdraw/dismiss', $data, 'urlencoded', 'GET');
        }
        write_log('Account','setStatus',['pay_type'=>$pay_type,'data'=>$data,'res'=>$res]);
        if ($res && $res['code'] == 0) {
            OperationLogs::createData($request, OperationLogs::ACCOUNT, [2 => '驳回', 3 => '提现'][$pay_status], $order_sn);
            return $this->toJson();
        }
        return $this->toJson(self::ERROR, [], $res['msg']);
    }

    /**
     * 批量驳回
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function multiReject(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'order_sn' => 'bail|required|array'
        ], [
            'order_sn.required' => '参数不可为空',
            'order_sn.array' => '参数必须为数组'
        ]);
        if ($validator->fails()) {
            return $this->toJson(self::SUCCESS, $validator->errors()->all()[0]);
        }
        $kkaudio_api = config('kkaudio.kkaudio_api');
        $total = count($request->input('order_sn'));
        $succeed = $fail = 0;
        $failOrderSn = '';
        foreach ($request->input('order_sn') as $order_sn) {
            $res = curl_request($kkaudio_api . '/finance/withdraw/dismiss', ['order_sn' => $order_sn], 'urlencoded', 'GET');
            if ($res['code'] == 0) {
                $succeed++;
            } else {
                $fail++;
                $failOrderSn .= $order_sn . "#";
            }
        }
        trim($failOrderSn, '#');
        OperationLogs::createData($request, OperationLogs::ACCOUNT, "批量驳回",$request->input('order_sn'));
        return $this->toJson(self::SUCCESS, [], "总数:{$total} 成功:{$succeed}  失败:{$fail}  失败订单号:{$failOrderSn}");
    }

    public function accountStatistics(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'page' => 'required|integer|min:1',
            'limit' => 'required|integer',
            'start_date' => 'nullable|date_format:Y-m-d',
            'end_date' => 'nullable|date_format:Y-m-d',
            'type' => 'nullable', Rule::in('d', 'm')
        ], [
            'start_date.date_format' => '开始时间日期格式错误',
            'end_date.date_format' => '结束时间日期格式错误',
        ]);

        if ($validator->fails()) {
            return $this->toJson(self::PARAM_ERROR, [], $validator->errors()->all()[0]);
        }

        return $this->toJson(self::SUCCESS, $this->model->accountStatistics($request->all()));
    }

    /**
     * 充值流水
     * @param Request $request
     * @param FinanceRechargeOrder $financeRechargeOrder
     * @return \Illuminate\Http\JsonResponse
     */
    public function rechargeRecordList(Request $request, FinanceRechargeOrder $financeRechargeOrder)
    {
        return $this->toJson(self::SUCCESS, $financeRechargeOrder->getList($request));
    }

    /**
     * 财富值流水
     * @param Request $request
     * @param FinanceCharmStream $financeCharmStream
     * @return \Illuminate\Http\JsonResponse
     */
    public function charmRecordList(Request $request, FinanceCharmStream $financeCharmStream)
    {
        return $this->toJson(self::SUCCESS, $financeCharmStream->getList($request));
    }

    /**
     * 魅力值流水
     * @param Request $request
     * @param FinanceWealthStream $financeWealthStream
     * @return \Illuminate\Http\JsonResponse
     */
    public function wealthRecordList(Request $request, FinanceWealthStream $financeWealthStream)
    {
        return $this->toJson(self::SUCCESS, $financeWealthStream->getList($request));
    }

    /**
     * 钻石流水
     * @param Request $request
     * @param FinanceDiamondStream $financeDiamondStream
     * @return \Illuminate\Http\JsonResponse
     */
    public function diamondRecordList(Request $request, FinanceDiamondStream $financeDiamondStream)
    {
        return $this->toJson(self::SUCCESS, $financeDiamondStream->getList($request));
    }

    /**
     * 对账记录
     * @param Request $request
     * @param CheckRecord $checkRecord
     * @return \Illuminate\Http\JsonResponse
     */
    public function checkRecords(Request $request, CheckRecord $checkRecord)
    {
        return $this->toJson(self::SUCCESS, $checkRecord->getList($request));
    }

    /**
     * 对账
     * @param Request $request
     * @param $check_id
     * @param CheckRecord $checkRecord
     * @return \Illuminate\Http\JsonResponse
     */
    public function setRealRechargePrice(Request $request, $check_id, CheckRecord $checkRecord)
    {
        $validator = Validator::make($request->all(), [
            'real_recharge_price' => 'bail|required|numeric'
        ], [
            'real_recharge_price.required' => '对账金额必须',
            'real_recharge_price.numeric' => '对账金额必须为有效的数字'
        ]);
        if ($validator->fails()) {
            return $this->toJson(self::ERROR, [], $validator->errors()->all()[0]);
        }

        if ($request->input('real_recharge_price') > $request->input('recharge_price')) {
            return $this->toJson(self::ERROR, [], '实际金额必须小于等于充值金额');
        }

        $checkRecord->setRealRechargePrice($request, $check_id);
        OperationLogs::createData($request, OperationLogs::ACCOUNT, '对账记录');
        return $this->toJson(self::SUCCESS);
    }

    public function getOverheadCost(Request $request, CostStatistics $costStatistics)
    {
        return $this->toJson(self::SUCCESS, $costStatistics->getList($request));
    }

    public function withdrawAuditAll(Request $r,Number $number, FinanceWithdrawOrder $financeWithdrawOrder)
    {
        $number->getForbidList();
        $accountType = $r->account_type ?? 0;
        $forbid_user = array_keys($number->forbidUser);
        $forbid_user = implode(',', $forbid_user);
        return $this->toJson(self::SUCCESS, $financeWithdrawOrder->statisticsWithdrawAuditAll($forbid_user,$accountType));
    }

    public function getOrSetChannelRadio(Request $request)
    {
        $input = $request->input();
        $res = curl_request(getKkaudioApiUrl() . '/inner/finance/recharge/channel/ratio', $input, 'urlencoded', 'GET');
        return $this->toJson(self::SUCCESS, $res);

    }



}
